package com.campus.food.service.impl;

import com.campus.food.mapper.OrderDetailMapper;
import com.campus.food.mapper.OrderMapper;
import com.campus.food.mapper.FoodMapper;
import com.campus.food.model.entity.OrderDetail;
import com.campus.food.model.entity.Order;
import com.campus.food.model.entity.Food;
import com.campus.food.service.OrderDetailService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;

/**
 * 订单详情服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class OrderDetailServiceImpl implements OrderDetailService {
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Override
    public OrderDetail addOrderDetail(OrderDetail orderDetail) {
        // 验证必填字段
        validateOrderDetail(orderDetail);
        
        // 检查订单是否存在
        Order order = orderMapper.selectById(orderDetail.getOrderId());
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查菜品是否存在
        Food food = foodMapper.selectById(orderDetail.getFoodId());
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        // 设置菜品信息（快照）
        orderDetail.setFoodName(food.getName());
        orderDetail.setFoodImage(food.getImage());
        orderDetail.setPrice(food.getPrice());
        
        // 计算小计
        BigDecimal subtotal = food.getPrice().multiply(new BigDecimal(orderDetail.getQuantity()));
        orderDetail.setSubtotal(subtotal);
        
        // 保存订单详情
        int result = orderDetailMapper.insert(orderDetail);
        if (result <= 0) {
            throw new BusinessException("添加订单详情失败");
        }
        
        return orderDetail;
    }
    
    @Override
    @Transactional(readOnly = true)
    public OrderDetail getOrderDetailById(Long id) {
        if (id == null) {
            throw new BusinessException("订单详情ID不能为空");
        }
        
        OrderDetail orderDetail = orderDetailMapper.selectById(id);
        if (orderDetail == null) {
            throw new BusinessException("订单详情不存在");
        }
        
        return orderDetail;
    }
    
    @Override
    public boolean updateOrderDetail(OrderDetail orderDetail) {
        if (orderDetail.getId() == null) {
            throw new BusinessException("订单详情ID不能为空");
        }
        
        // 验证必填字段
        validateOrderDetail(orderDetail);
        
        // 检查订单详情是否存在
        OrderDetail existingOrderDetail = orderDetailMapper.selectById(orderDetail.getId());
        if (existingOrderDetail == null) {
            throw new BusinessException("订单详情不存在");
        }
        
        // 重新计算小计
        if (orderDetail.getQuantity() != null && orderDetail.getPrice() != null) {
            BigDecimal subtotal = orderDetail.getPrice().multiply(new BigDecimal(orderDetail.getQuantity()));
            orderDetail.setSubtotal(subtotal);
        }
        
        return orderDetailMapper.updateById(orderDetail) > 0;
    }
    
    @Override
    public boolean deleteOrderDetail(Long id) {
        if (id == null) {
            throw new BusinessException("订单详情ID不能为空");
        }
        
        // 检查订单详情是否存在
        OrderDetail orderDetail = orderDetailMapper.selectById(id);
        if (orderDetail == null) {
            throw new BusinessException("订单详情不存在");
        }
        
        return orderDetailMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<OrderDetail> getOrderDetailsByOrderId(Long orderId) {
        if (orderId == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        return orderDetailMapper.selectByOrderId(orderId);
    }
    
    @Override
    public boolean deleteOrderDetailsByOrderId(Long orderId) {
        if (orderId == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        return orderDetailMapper.deleteByOrderId(orderId) >= 0; // 即使没有数据也返回true
    }
    
    @Override
    public boolean addOrderDetailsBatch(List<OrderDetail> orderDetails) {
        if (orderDetails == null || orderDetails.isEmpty()) {
            throw new BusinessException("订单详情列表不能为空");
        }
        
        // 验证每个订单详情
        for (OrderDetail orderDetail : orderDetails) {
            validateOrderDetail(orderDetail);
            
            // 检查菜品是否存在并设置菜品信息
            Food food = foodMapper.selectById(orderDetail.getFoodId());
            if (food == null) {
                throw new BusinessException("菜品不存在：" + orderDetail.getFoodId());
            }
            
            // 设置菜品信息（快照）
            orderDetail.setFoodName(food.getName());
            orderDetail.setFoodImage(food.getImage());
            orderDetail.setPrice(food.getPrice());
            
            // 计算小计
            BigDecimal subtotal = food.getPrice().multiply(new BigDecimal(orderDetail.getQuantity()));
            orderDetail.setSubtotal(subtotal);
        }
        
        return orderDetailMapper.insertBatch(orderDetails) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<OrderDetail> getOrderDetailsByFoodId(Long foodId) {
        if (foodId == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        return orderDetailMapper.selectByFoodId(foodId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Integer getSalesCountByFoodId(Long foodId) {
        if (foodId == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        Integer count = orderDetailMapper.selectSalesCountByFoodId(foodId);
        return count != null ? count : 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<OrderDetail> getOrderDetailsByOrderIds(List<Long> orderIds) {
        if (orderIds == null || orderIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<OrderDetail> allOrderDetails = new ArrayList<>();
        for (Long orderId : orderIds) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
            allOrderDetails.addAll(orderDetails);
        }
        
        return allOrderDetails;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Double calculateOrderDetailTotal(Long orderId) {
        if (orderId == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
        if (orderDetails.isEmpty()) {
            return 0.0;
        }
        
        BigDecimal total = BigDecimal.ZERO;
        for (OrderDetail orderDetail : orderDetails) {
            if (orderDetail.getSubtotal() != null) {
                total = total.add(orderDetail.getSubtotal());
            }
        }
        
        return total.doubleValue();
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean validateOrderDetails(Long orderId) {
        if (orderId == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);
        if (orderDetails.isEmpty()) {
            return false;
        }
        
        // 验证每个订单详情的数据完整性
        for (OrderDetail orderDetail : orderDetails) {
            // 检查必填字段
            if (orderDetail.getFoodId() == null || 
                !StringUtils.hasText(orderDetail.getFoodName()) ||
                orderDetail.getPrice() == null ||
                orderDetail.getQuantity() == null ||
                orderDetail.getSubtotal() == null) {
                return false;
            }
            
            // 检查数量和价格的合理性
            if (orderDetail.getQuantity() <= 0 || 
                orderDetail.getPrice().compareTo(BigDecimal.ZERO) <= 0 ||
                orderDetail.getSubtotal().compareTo(BigDecimal.ZERO) <= 0) {
                return false;
            }
            
            // 验证小计计算是否正确
            BigDecimal expectedSubtotal = orderDetail.getPrice().multiply(new BigDecimal(orderDetail.getQuantity()));
            if (orderDetail.getSubtotal().compareTo(expectedSubtotal) != 0) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 验证订单详情信息
     */
    private void validateOrderDetail(OrderDetail orderDetail) {
        if (orderDetail == null) {
            throw new BusinessException("订单详情信息不能为空");
        }
        
        if (orderDetail.getOrderId() == null) {
            throw new BusinessException("订单ID不能为空");
        }
        
        if (orderDetail.getFoodId() == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        if (orderDetail.getQuantity() == null || orderDetail.getQuantity() <= 0) {
            throw new BusinessException("菜品数量必须大于0");
        }
        
        if (orderDetail.getQuantity() > 99) {
            throw new BusinessException("单个菜品数量不能超过99个");
        }
    }
} 